<?php

namespace App\Http\Controllers\Api\V6;

use App\Http\Controllers\Service\WeixinBuyVip;
use App\Http\Controllers\Weixin\WeixinServiceController;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Http\Controllers\Weixin\WeixinServiceController AS WeixinService;
use App\Models\V6\MemberModel;
use EasyWeChat\Payment\Order;
use DB;
use App\Http\Controllers\admin_system\LiveController as AdminLiveController;
class WeiXinController extends Controller
{


    /**
     * 获得支付的数据
     * */
    public function get_pay_data(Request $request)
    {
        header("Access-Control-Allow-Origin: *");
        $goodsType  = $request->input('goodsType');
        $goodsId    = $request->input('goodsId');
        $goodsNumber= $request->input('goodsNumber',1);
        $money      = round($request->input('money',0),2);
        $userId     = $request->input('tokenUserId');

        $data   = [
            'userId'    => [$userId,1002,'缺少用户'],
            'type'      => [$goodsType,1003,'缺少类型'],
            'id'        => [$goodsId,1004,'缺少产品ID']
        ];

        $result = $this->check_params($data);
        if(!$result->status)
        {
            return apiData()->send($result->code,$result->message);
        }

        $memberModel    = new MemberModel();
        $memberInfo     = $memberModel->get_member_info_by_id($userId);
        if(!$memberInfo)
        {
            return apiData()->send(2001,'用户不存在');
        }
        $wxService  = new WeixinService();
        $app        = $wxService->get_oauth_client_app();
        $payment    = $app->payment;


        //获得订单信息
        switch($goodsType)
        {
            case 'lhld'://老侯论道音频
                $orderData  = new wxOrder();
                $orderData->tradeNo = create_member_number();
                $orderData->payDesc = "打赏老侯论道";
                $orderData->callback= url('api/v5/weixin/lhldPayCallback');
                $orderData->money   = $money;
                break;
            case 'book':
                $orderData  = new wxOrder();
                $orderData->tradeNo = create_member_number();
                $orderData->payDesc = "打赏老侯代读";
                $orderData->callback= url('api/v5/weixin/lhldPayCallback');
                $orderData->money   = $money;
                break;

            default://直播打赏
                if("live" == substr($goodsType,0,4))
                {
                    $orderData  = $this->add_live_pay_order(substr($goodsType,6),$goodsId,$goodsNumber);
                }
                break;

        }

        if($orderData->money < 0.01 || $orderData->money > 10000)
        {
            return apiData()->send(4005,'金额不能少于1分或大于1万');
        }
        $attributes = [
            'trade_type'       => 'APP', // JSAPI，NATIVE，APP...
            'body'             => $orderData->payDesc,
            'detail'           => 'xxxxx',
            'out_trade_no'     => $orderData->tradeNo,
            'total_fee'        => $orderData->money * 100,  // 单位：分
            'notify_url'       => $orderData->callback,             // 支付结果通知网址，如果不设置则会使用配置里的默认地址
            'attach'           => 'uid='.$memberInfo->UserID.'&gid='.$goodsId."&gtype=".$goodsType
        ];

        //创建一个支付订单
        $order = new Order($attributes);

        //获得支付数据
        $result = $payment->prepare($order);

        if ($result->return_code == 'SUCCESS' && $result->result_code == 'SUCCESS')
        {
            $prepayId = $result->prepay_id;
        }
        else
        {
            return apiData()->send(4001,$result->return_msg);
        }
        $appConfig = $payment->configForAppPayment($prepayId);

        //记录订单
        $wxPayData  = [
            'user_id'   => $memberInfo->UserID,
            'trade_no'  => $orderData->tradeNo,
            'goods_type'=> $goodsType,
            'goods_id'  => $goodsId,
            'order_money'=>$orderData->money,
            'created_at'=> date_time(),
            'message'   => $request->input('message','')
        ];
        DB::table('wx_app_pay_log')->insert($wxPayData);
        return apiData()
            ->set_data('appPayConfig',$appConfig)
            ->send(200,'ok');
    }




    /**
     * 新增直播支付订单
     * @param $liveId int 直播ID
     * @param $giftId int 赠的礼物的ID
     * @param $number int 礼物的数量
     * */
    private function add_live_pay_order($liveId,$giftId,$number)
    {
        $giftInfo = DB::table('live_gift_list')
            ->where('id',$giftId)
            ->whereNull('deleted_at')
            ->first();

        $money  = $giftInfo->price * $number;
        $orderData  = new wxOrder();
        $orderData->callback    = url('api/v4/weixin/livePayCallback');
        $orderData->money       = $money;
        $orderData->tradeNo     = create_member_number();
        $orderData->payDesc     = "直播打赏";
        return $orderData;
    }



    /**
     * 老侯论道支付回调
     * */
    public function lhld_pay_callback(Request $request)
    {
        $weixinService  = new WeixinService();
        $app            = $weixinService->get_oauth_client_app();
        $adminLiveController            = new AdminLiveController();
        $memberModel                    = new MemberModel();

        $GLOBALS['memberModel']         = $memberModel;
        $GLOBALS['adminLiveController'] = $adminLiveController;
        $GLOBALS['wxservice']           = $weixinService;

        $response = $app->payment->handleNotify(function($notify, $successful){
            // 你的逻辑
            $attach     = $notify->attach;
            $attachs    = explode('&',$attach);
            foreach($attachs as $v)
            {
                $values = explode('=',$v);
                $attachs[$values[0]] = $values[1];
            }

            $userId     = $attachs['uid'];

            //$memberInfo = $GLOBALS['memberModel']->get_member_info_by_id($userId);

            /*
            $notice     = [
                'rewarder'      => $memberInfo->YourName,
                'rewarderHead'  => change_member_head_img($memberInfo->FilePath1),
                'giftImg'       => env('HOST')."/".$goodsInfo->img_url,
                'giftInfo'      => "打赏了一个".$goodsInfo->name,
            ];*/



            $tradeNo    = $notify->out_trade_no;    //订单号
            $updateInfo = [
                'pay_time'          => $notify->time_end,
                'transaction_id'    => $notify->transaction_id,
                'pay_money'         => $notify->total_fee,
                'openid'            => $notify->openid,
                'pay_status'        => 1
            ];
            DB::table('wx_app_pay_log')->where('trade_no',$tradeNo)->update($updateInfo);

            return true; // 或者错误消息
        });
        return $response; // Laravel 里请使用：return $response;
    }


    /**
     * 微信支付回调
     * */
    public function live_pay_callback(Request $request)
    {
        $weixinService  = new WeixinService();
        $app            = $weixinService->get_oauth_client_app();
        $adminLiveController            = new AdminLiveController();
        $memberModel                    = new MemberModel();

        $GLOBALS['memberModel']         = $memberModel;
        $GLOBALS['adminLiveController'] = $adminLiveController;
        $GLOBALS['wxservice']           = $weixinService;

        $response = $app->payment->handleNotify(function($notify, $successful){
            // 你的逻辑
            $attach     = $notify->attach;
            $attachs    = explode('&',$attach);
            foreach($attachs as $v)
            {
                $values = explode('=',$v);
                $attachs[$values[0]] = $values[1];
            }

            $userId     = $attachs['uid'];
            $goodsId    = $attachs['gid'];
            $memberInfo = $GLOBALS['memberModel']->get_member_info_by_id($userId);
            $goodsInfo  = DB::table('live_gift_list')->where('id',$goodsId)->first();

            $notice     = [
                'rewarder'      => $memberInfo->YourName,
                'rewarderHead'  => change_member_head_img($memberInfo->FilePath1),
                'giftImg'       => env('HOST')."/".$goodsInfo->img_url,
                'giftInfo'      => "打赏了一个".$goodsInfo->name,
            ];


            $GLOBALS['adminLiveController']->send_group_system_notification($notice);

            $tradeNo    = $notify->out_trade_no;    //订单号
            $updateInfo = [
                'pay_time'          => $notify->time_end,
                'transaction_id'    => $notify->transaction_id,
                'pay_money'         => $notify->total_fee,
                'openid'            => $notify->openid,
                'pay_status'        => 1
            ];
            DB::table('wx_app_pay_log')->where('trade_no',$tradeNo)->update($updateInfo);

            return true; // 或者错误消息
        });
        return $response; // Laravel 里请使用：return $response;
    }


    /**
     * 获得微信订单
     * */
    public function get_wx_pay_orders(Request $request)
    {
        $goodsType  = $request->input('goodsType','');
        $goodsId    = $request->input('goodsId');

        $orders     = DB::table('wx_app_pay_log as a')
            ->leftJoin('memberinfo as b','a.user_id','=','b.UserID')
            ->where('a.goods_type',$goodsType)
            ->where('a.goods_id',$goodsId)
            ->where('a.pay_status',1)
            ->select('a.order_money','a.pay_time','a.message','b.YourName','b.FilePath1')
            ->get();

        foreach($orders as $order)
        {
            $order->FilePath1 = change_member_head_img($order->FilePath1);
        }

        return apiData()->set_data('orders',$orders)->send(200,'ok');
    }


    /**
     * 小程序购买VIP服务
     *
     * */
    public function buy_vip(Request $request){

        $userId         = $request->input('userId');
        $version        = $request->input('version',1);
        $platform       = $request->input('platform','');
        $openIos        = system_log("ios_mini_buy") == 1 ? true : false;
        
        if($platform == 'ios' && $openIos == false){

            return apiData()->send(2001,"受平台限制，ios暂不可用");
        }

        $weixinService  = new WeixinServiceController();
        $memberModel    = new MemberModel();
        $memberInfo     = $memberModel->get_member_info_by_id($userId);
        $money          = system_log('vip_price');//购买价格
        $orderSn        = create_member_number();
        $openid         = $memberInfo->mini_openid;
        $title          = "教导读书会一年VIP特权";
        $detail         = $title;
        $callbackUrl    = url("api/v6/weixin/buy_vip_callback",[],true);
        $payConfig      = $weixinService->get_miniapp_pay_config($openid, $money, $orderSn, $title, $detail, $callbackUrl);
        $payConfig['orderSn']   = $orderSn;
        //添加订单
        $goodsName  = "vip";
        $goodsId    = 1;
        $m          = $memberInfo;
        $prepayId   = $payConfig['prepayId'];

        WeixinBuyVip::add_wx_order("miniapp",$goodsName,$goodsId,$money,$orderSn,$m->wx_unionid,$m->mini_openid,$m->YourName,$userId,$prepayId);

        return apiData()->set_data('config',$payConfig)->send();
    }

    /**
     * 购买回调
     * */
    public function buy_vip_callback(Request $request){

        $weixinService      = new WeixinServiceController();
        $miniApp            = $weixinService->miniApp();

        $response           = $miniApp->payment->handleNotify(function($notify,$successful) use ($weixinService)
        {
            $orderInfo      = WeixinBuyVip::hand_buy_vip_result($notify,'miniapp');

            if($orderInfo){

                //发送通知消息
                $openId         = $orderInfo->openid;
                $orderSn        = $orderInfo->trade_no;
                $money          = "".$orderInfo->order_money;
                $content        = "您已开通教导读书会VIP特权";
                $note           = "如有疑问，请致电...";

                $weixinService->send_miniapp_buy_vip_success_msg($openId,$orderSn,$money,$content,$note,$orderInfo->prepay_id);
            }

        });

        return response("<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>");
        //return $response->send();
    }

    /**
     * 获取token
     * */
    public function get_access_token(){
        $weixinService      = new WeixinServiceController();
        $miniApp            = $weixinService->miniApp();
        $token              = $miniApp->access_token->getToken();

        return apiData()->set_data("access_token",$token)->send();
    }
}




class wxOrder{
    public  $payDesc;
    public $money;
    public $tradeNo;
    public $callback;
}